package com.enjoyread.core.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.enjoyread.common.config.SystemConfig;
import com.enjoyread.common.utils.DateUtil;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;

public class AliOssUtils {
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    public static final String endpoint = "oss-cn-beijing.aliyuncs.com";
    public static final String bucketName = "enjoy-read";
    private static OSS client;
    static {
       client=new OSSClientBuilder().build(endpoint, SystemConfig.OSS_KEY, SystemConfig.OSS_KEYSECRET);
    }
    /**
     * 上传内容*/
    public static String upload(String objName,String content){
        //实现内容上传
        client.putObject(bucketName, objName, new ByteArrayInputStream(content.getBytes()));
        //生成访问地址
        return createUrl(objName, DateUtil.getDateYear(SystemConfig.OSS_URL_TIME));
    }
    /**
     * 上传文件*/
    public static String upload(String objName,byte[] data){
        //实现内容上传
        client.putObject(bucketName, objName, new ByteArrayInputStream(data));
        //生成访问地址
        return createUrl(objName, DateUtil.getDateYear(SystemConfig.OSS_URL_TIME));
    }
    /**
     * 上传文件*/
    public static String upload(String objName,byte[] data,Date cdate){
        //实现内容上传
        client.putObject(bucketName, objName, new ByteArrayInputStream(data));
        //生成访问地址
        return createUrl(objName, cdate);
    }
    /**
     * 上传文件*/
    public static String upload(String objName, InputStream data){
        //实现内容上传
        client.putObject(bucketName, objName, data);
        //生成访问地址
        return createUrl(objName, DateUtil.getDateYear(SystemConfig.OSS_URL_TIME));
    }
    /*生成访问路径*/
    public static String createUrl(String objName, Date date){
        return client.generatePresignedUrl(bucketName,objName,date).toString();
    }
    /**
     * 删除文件*/
    public static boolean delObject(String objName){
        try{
            client.deleteObject(bucketName,objName);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
